<template>
  <BasicDrawer
    :destroyOnClose="true"
    v-bind="$attrs"
    @register="registerDrawer"
    :title="title"
    width="840px"
    okText="确定"
    @ok="closeDrawer"
    @close="closeDrawer"
    :maskClosable="false"
    showFooter
  >
    <template #footer>
      <div v-if="chooseProduct == false"></div >
      <div v-else>
        <a-button danger @click="closeDrawer()">取消</a-button>&nbsp;
        <a-popconfirm
          v-if="recordRef.status === 1"
          title="您确定停售要吗?"
          ok-text="确定"
          cancel-text="取消"
          @confirm="onStop"
        >
          <a-button danger> 停售</a-button>
        </a-popconfirm>&nbsp;
        <a-button v-else danger @click="onSale"> 在售</a-button>&nbsp;
        <a-button type="primary" @click="onEdit">编辑</a-button>
      </div>
    </template>

    <div class="card">
      <div class="c-head">
        <a-flex gap="large" align="center">
          <div class="img-container">
            <a-image
              :width="136"
              :height="136"
              :src="OSS_IMG_URL(recordRef.goodsImage || recordRef.cardImage)"
              :fallback="imgErrSrc"
            />
          </div>

          <a-flex class="right" vertical gap="middle">
            <div class="cn-medium title">{{ recordRef.goodsName || recordRef.cardName }}</div>

            <div class="price"
              ><span class="d-regular value">{{ recordRef.salePrice }}</span
              ><span class="unit">元</span></div
            >

            <a-flex gap="small">
              <div class="cell" v-if="cateType === 'C'">{{
                getChildrenLabel(proCardType, cardType, cardSubType)
              }}</div>
              <div class="cell" v-else>{{ getLabel(proCategoryType2, cateType) }}</div>

              <div class="cell">{{ getLabel(proStatus, recordRef.status) }}</div>
              <div class="cell">{{ getLabel(proSource, recordRef.source) }}</div>
            </a-flex>

            <div class="fill"></div>
            <div class="desc" v-if="cateType === 'P'"> 规格：{{ recordRef.specs }}</div>
            <div class="desc" v-else-if="cateType === 'S'">
              服务时长：{{ recordRef.duration }}分钟
            </div>
            <div class="desc" v-else-if="cateType === 'C'">
              <span v-if="cardSubType === '201' || cardSubType === '203'"
                >共<span class="d-medium total">{{ recordRef.oriPoint || 0 }}次，</span></span
              >
              <span>{{ getValidDesc(recordRef) }}</span>
            </div>
          </a-flex>
        </a-flex>
      </div>

      <div class="c-body">
        <div v-show="cateType === 'S'" style="margin: 16px 0">
          <div class="c-title" style="margin: 0 0 8px 8px"> 产品消耗</div>

          <BasicTable @register="S.registerTable" :dataSource="S.dataSource" :scroll="{ y: 320 }" />
        </div>

        <div v-show="exist(cardSubType, ['201', '202', '203'])" style="margin: 16px 0">
          <div class="c-title" style="margin: 0 0 8px 8px"> 购卡权益</div>
          <BasicTable
            @register="C.G.registerTable"
            :dataSource="C.G.dataSource"
            :scroll="{ y: 320 }"
          />
        </div>

        <div v-show="cateType === 'C'" style="margin: 16px 0">
          <div class="c-title" style="margin: 0 0 8px 8px"> 赠送权益</div>

          <a-tabs v-model:activeKey="C.cateType" type="card" class="card-tabs">
            <a-tab-pane v-for="o in proCategoryType2" :key="o.value" :tab="o.label">
              <BasicTable
                @register="C[o.value].registerTable"
                :dataSource="C[o.value].dataSource"
                :scroll="{ y: 320 }"
              />
            </a-tab-pane>
          </a-tabs>
        </div>

        <a-row :gutter="[32, 16]">
          <template v-if="cateType === 'P'">
            <a-col :span="4" class="label"> 单位</a-col>
            <a-col :span="18" class="value">
              {{ getUnitText(recordRef) }}
            </a-col>
            <a-col :span="4" class="label"> 单位换算</a-col>
            <a-col :span="18" class="value">
              {{ getConvertUnitText(recordRef) }}
            </a-col>

            <a-col :span="4" class="label"> 安全存量</a-col>
            <a-col :span="18" class="value">
              <div v-if="recordRef.safeStock">{{ recordRef.safeStock || '-' }} {{ recordRef.saleUnit || defaultUnit }}</div>
              <div v-else>-</div>
            </a-col>
            <a-col :span="4" class="label"> 回购提醒</a-col>
            <a-col :span="18" class="value"> {{ recordRef.alertStock ? recordRef.alertStock + '天' : '-' }}</a-col>
          </template>
          <template v-else-if="cateType === 'S'">
            <a-col :span="4" class="label"> 回访间隔</a-col>
            <a-col :span="18" class="value"> {{ recordRef.visitBack ? recordRef.visitBack + '天' : '-' }}</a-col>

            <a-col :span="4" class="label"> 消费间隔提醒</a-col>
            <a-col :span="18" class="value"> {{ recordRef.csmInterval ? recordRef.csmInterval + '天' : '-' }}</a-col>
          </template>

          <template v-if="!!recordRef.cardVideo || !!recordRef.goodsVideo">
            <a-col :span="4" class="label"> 商品视频</a-col>
            <a-col :span="18" class="value">
              <vue3-video-play
                width="80%"
                height="auto"
                :src="recordRef.cardVideo || recordRef.goodsVideo"
              />
            </a-col>
          </template>

          <a-col :span="4" class="label"> 商品描述</a-col>
          <a-col :span="18" class="value">
            {{ recordRef.sellPoint }}
          </a-col>
        </a-row>
      </div>
    </div>
  </BasicDrawer>
</template>
<script>
  import { defineComponent, h, reactive, ref, toRefs } from 'vue';
  import { BasicDrawer, useDrawerInner } from '@/components/Drawer';

  import {
    getLabel,
    imgErrSrc,
    proStatus,
    OSS_IMG_URL,
    proCategoryType2,
    proSource,
    getChildrenLabel,
    proCardType,
  } from '@/api/ds';
  import { GET, POST, PUT } from '@/api/http';
  import { useMessage } from '@/hooks/web/useMessage';
  import { getUnitText, getConvertUnitText, defaultUnit, getValidDesc } from './util';
  import { BasicTable, useTable } from '@/components/Table';
  import { useRouter } from 'vue-router';
  import ProImgCell from '@/widget/pro-img-cell.vue';
  import { exist } from '@/api/util.js';

  export default defineComponent({
    components: { BasicTable, BasicDrawer },
    emits: ['complete'],
    setup(_, { emit }) {
      const { createMessage } = useMessage();
      const router = useRouter();

      const [registerTableS] = useTable({
        columns: [
          {
            title: '产品名称',
            dataIndex: 'goodsName',
            ellipsis: false,
            width: 290,
            customRender: ({ value: title, record }) =>
              h(ProImgCell, { src: record.goodsImage, title }),
          },

          {
            title: '消耗',
            dataIndex: 'csmValue',
            ellipsis: false,
          },

          {
            title: '单位',
            dataIndex: 'saleUnit',
            ellipsis: false,
          },
        ],
        pagination: false,
        useSearchForm: false,
        showTableSetting: false,
        bordered: true,
        showIndexColumn: false,
        rowKey: 'goodsSn',
      });

      const [registerTableCG] = useTable({
        columns: [
          {
            title: '服务名称',
            dataIndex: 'goodsName',
            ellipsis: false,
            width: 290,
            customRender: ({ value: title, record }) =>
              h(ProImgCell, { src: record.goodsImage, title }),
          },

          {
            title: '服务时长',
            dataIndex: 'duration',
            ellipsis: false,
            customRender: ({ value }) => `${value ?? 0}分钟`,
          },

          {
            title: '服务价格',
            dataIndex: 'salePrice',
            ellipsis: false,
            customRender: ({ value }) => `${value ?? 0}元`,
          },

          {
            title: '次数',
            dataIndex: 'qty',
            ellipsis: false,
            customRender: ({ value }) => `${value ?? 0}次`,
            ifShow: () => state.cardSubType === '201',
          },
        ],
        pagination: false,
        useSearchForm: false,
        showTableSetting: false,
        bordered: true,
        showIndexColumn: false,
        rowKey: 'goodsSn',
      });

      const [registerTableCP] = useTable({
        columns: [
          {
            title: '产品名称',
            dataIndex: 'goodsName',
            ellipsis: false,
            width: 290,
            customRender: ({ value: title, record }) =>
              h(ProImgCell, { src: record.goodsImage, title }),
          },

          {
            title: '规格',
            dataIndex: 'specs',
            ellipsis: false,
          },

          {
            title: '售卖价格',
            dataIndex: 'salePrice',
            ellipsis: false,
            customRender: ({ value }) => `${value ?? 0}元`,
          },

          {
            title: '赠送数量',
            dataIndex: 'qty',
            ellipsis: false,
          },
        ],
        pagination: false,
        useSearchForm: false,
        showTableSetting: false,
        bordered: true,
        showIndexColumn: false,
        rowKey: 'goodsSn',
      });

      const [registerTableCS] = useTable({
        columns: [
          {
            title: '服务名称',
            dataIndex: 'goodsName',
            ellipsis: false,
            width: 290,
            customRender: ({ value: title, record }) =>
              h(ProImgCell, { src: record.goodsImage, title }),
          },

          {
            title: '服务时长',
            dataIndex: 'duration',
            ellipsis: false,
            customRender: ({ value }) => `${value ?? 0}分钟`,
          },

          {
            title: '服务价格',
            dataIndex: 'salePrice',
            ellipsis: false,
            customRender: ({ value }) => `${value ?? 0}元`,
          },

          {
            title: '赠送次数',
            dataIndex: 'qty',
            ellipsis: false,
          },
        ],
        pagination: false,
        useSearchForm: false,
        showTableSetting: false,
        bordered: true,
        showIndexColumn: false,
        rowKey: 'goodsSn',
      });

      const [registerTableCC] = useTable({
        columns: [
          {
            title: '卡项名称',
            dataIndex: 'cardName',
            ellipsis: false,
            width: 290,
            customRender: ({ value: title, record }) =>
              h(ProImgCell, { src: record.cardImage, title }),
          },

          {
            title: '卡项类型',
            dataIndex: 'cardSubType',
            ellipsis: false,
            customRender: ({ record }) =>
              getChildrenLabel(proCardType, record.cardType, record.cardSubType),
          },

          {
            title: '卡项价格',
            dataIndex: 'salePrice',
            ellipsis: false,
            customRender: ({ value }) => `${value ?? 0}元`,
          },

          {
            title: '赠送次数',
            dataIndex: 'qty',
            ellipsis: false,
          },
        ],
        pagination: false,
        useSearchForm: false,
        showTableSetting: false,
        bordered: true,
        showIndexColumn: false,
        rowKey: 'goodsSn',
      });

      const state = reactive({
        title: '',

        cateType: null,
        cardType: null,
        cardSubType: null,

        imgErrSrc,
        proCategoryType2,
        proCardType,

        proStatus,
        proSource,
        defaultUnit,

        S: {
          registerTable: registerTableS,
          dataSource: [],
        },
        C: {
          G: {
            registerTable: registerTableCG,
            dataSource: [],
          },

          P: {
            registerTable: registerTableCP,
            dataSource: [],
          },
          S: {
            registerTable: registerTableCS,
            dataSource: [],
          },
          C: {
            registerTable: registerTableCC,
            dataSource: [],
          },
        },
      });

      const recordRef = ref({});

      async function getRecord(cateType, { id, batchNo }) {
        let record = null;

        if (cateType === 'P') {
          record = await GET('/product/productStoreDetail', { productId: id });
        } else if (cateType === 'S') {
          record = await GET('/product/serviceStoreDetail', { serviceId: id });
        } else if (cateType === 'C') {
          record = await POST('/card/getCardBatchInfoBean', { batchNo });
        }

        return record;
      }

      let chooseProduct = ref({})

      const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(
        async ({ choose, cateType, record: detail }) => {
          chooseProduct.value = choose
          console.log(chooseProduct.value)
          state.title = getLabel(proCategoryType2, cateType) + '详情';
          state.cateType = cateType;

          const { id, batchNo } = detail || {};
          recordRef.value = (await getRecord(cateType, { id, batchNo })) || {};

          const { cardType, cardSubType } = recordRef.value || {};
          state.cardType = cardType;
          state.cardSubType = cardSubType;

          if (cateType === 'S') {
            //疗程服务
            const { consumeList } = recordRef.value;

            //统一命名
            consumeList?.forEach((o) => {
              const { productGoodsName: goodsName, csmUnit: saleUnit } = o;
              Object.assign(o, { goodsName, saleUnit });
            });

            state.S.dataSource = consumeList;
          } else if (cateType === 'C') {
            //卡项-购卡权益
            const {
              paramCardBatchGoodsBeanList,
              apiResultStoreProductBeans,
              apiResultStoreServiceBeans,
              apiResultCardBatchInfoBeans,
            } = recordRef.value;

            //统一命名
            recordRef.value.apiResultCardBatchGoodsBeanList?.forEach((o) => {
              const { servicesName: goodsName, servicePrice: salePrice } = o;
              Object.assign(o, { goodsName, salePrice });
            });
            /* paramCardBatchGoodsBeanList?.forEach((o) => {
              const { servicesName: servicesName, servicePrice: salePrice } = o;
              Object.assign(o, { servicesName, salePrice });
            }); */

            apiResultStoreServiceBeans?.forEach((o) => {
              const { servicesName: goodsName, servicePrice: salePrice } = o;
              Object.assign(o, { goodsName, salePrice });
            });

            apiResultCardBatchInfoBeans?.forEach((o) => {
              const { cardName: goodsName, batchNo: goodsSn } = o;
              Object.assign(o, { goodsName, goodsSn });
            });

            state.C.G.dataSource = recordRef.value.apiResultCardBatchGoodsBeanList || [];
            state.C.P.dataSource = apiResultStoreProductBeans || [];
            state.C.S.dataSource = apiResultStoreServiceBeans || [];
            state.C.C.dataSource = apiResultCardBatchInfoBeans || [];
            /* state.C.P.dataSource = recordRef.value.apiResultStoreProductBeans || [];
            state.C.S.dataSource = recordRef.value.apiResultStoreServiceBeans || [];
            state.C.C.dataSource = recordRef.value.apiResultCardBatchInfoBeans || []; */
          }
        },
      );

      // 设置在售状态
      async function onSale() {
        const { cateType } = state;

        const { id, batchNo } = recordRef.value;
        const data = await getRecord(cateType, { id, batchNo });

        try {
          setDrawerProps({ confirmLoading: true });

          data.status = 1;
          if (cateType === 'P') {
            await PUT('/product/productStoreUpdate', data);
          } else if (cateType === 'S') {
            await PUT('/product/serviceStoreUpdate', data);
          } else if (cateType === 'C') {
            await POST('/card/updateCardBatch', data);
          }

          closeDrawer();
          createMessage.success(getLabel(proCategoryType2, cateType) + '已在售');
          emit('complete');
        } finally {
          setDrawerProps({ confirmLoading: false });
        }
      }

      async function onStop() {
        const { cateType } = state;

        const { id, batchNo } = recordRef.value;
        const data = await getRecord(cateType, { id, batchNo });

        try {
          setDrawerProps({ confirmLoading: true });

          data.status = 0;
          if (cateType === 'P') {
            await PUT('/product/productStoreUpdate', data);
          } else if (cateType === 'S') {
            await PUT('/product/serviceStoreUpdate', data);
          } else if (cateType === 'C') {
            await POST('/card/updateCardBatch', data);
          }

          closeDrawer();
          createMessage.success(getLabel(proCategoryType2, cateType) + '已停售');
          emit('complete');
        } finally {
          setDrawerProps({ confirmLoading: false });
        }
      }

      function onEdit() {
        const { cateType } = state;
        const { id, batchNo } = recordRef.value;

        const key = cateType === 'C' ? batchNo : id;
        router.push(`./list/edit?cateType=${cateType}&key=${key}`);

        closeDrawer();
      }

      return {
        ...toRefs(state),
        chooseProduct,
        recordRef,
        registerDrawer,
        closeDrawer,
        onStop,
        onSale,
        onEdit,
        getLabel,
        OSS_IMG_URL,
        getUnitText,
        getConvertUnitText,
        getChildrenLabel,
        getValidDesc,
        exist,
      };
    },
  });
</script>

<style lang="less" scoped>
  .card {
    margin: 8px 0 46px;
    padding: 12px;

    .c-title {
      display: flex;
      flex-direction: row;
      align-items: center;
      column-gap: 8px;
      color: #091f3d;
      font-size: 14px;
      font-weight: 600;
    }

    .c-head {
      margin-bottom: 32px;

      .img-container {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 160px;
        height: 160px;
        border-radius: 10px;
        // background-color: #f5f7fa;
        border: 1px solid #e5e5e5;
      }

      .right {
        .title {
          color: #091f3d;
          font-size: 18px;
        }

        .cell {
          padding: 4px 12px;
          border-radius: 4px;
          // background-color: #e0e5ec;
          color: @primary-color;
          border: 1px solid rgba(@primary-color, 0.4);
          font-size: 12px;
          font-weight: 400;
        }

        .price {
          color: @primary-color;

          .value {
            font-size: 18px;
            letter-spacing: 1px;
          }

          .unit {
            padding-left: 2px;
            font-size: 10px;
          }
        }

        .desc {
          color: #acb4bf;
          font-size: 12px;
        }
      }
    }

    .c-body {
      margin-top: 16px;

      .total {
        color: @primary-color;
        font-size: 16px;
      }

      .label {
        color: #acb4bf;
        text-align: left;
      }

      .value {
        color: #091f3d;
      }
    }
  }
</style>
